<template>
  <div class="catalog-image-generator">
    <!-- 触发按钮 -->
    <el-button
      :type="buttonType"
      :size="buttonSize"
      :icon="buttonIcon"
      :circle="!buttonText"
      :disabled="disabled"
      style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
      @click="showDialog"
    >
      {{ buttonText }}
    </el-button>

    <!-- 生成目录册图片抽屉 -->
    <el-drawer
      title="生成目录册图片"
      :visible.sync="dialogVisible"
      direction="rtl"
      size="90%"
      :append-to-body="true"
      :wrapper-closable="false"
      custom-class="catalog-drawer"
      @close="handleClose"
      @open="handleDialogOpen"
    >
      <div class="catalog-generator-content">
        <!-- 左右分栏布局 -->
        <div class="layout-container">
          <!-- 左侧：分组配置区域 -->
          <div class="left-panel">
            <!-- 固定在顶部的区域 -->
            <div class="fixed-header">
              <!-- 产品图片选择区域 -->
              <div v-if="images && images.length > 0" class="product-images-section">
                <div class="section-header" @click="productImagesCollapsed = !productImagesCollapsed">
                  <span class="section-title">
                    <i class="el-icon-picture" /> 报价单产品图片 ({{ images.length }})
                  </span>
                  <div class="section-actions">
                    <span class="section-hint">点击图片添加到当前分组</span>
                    <i :class="productImagesCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" class="collapse-icon" />
                  </div>
                </div>
                <div v-show="!productImagesCollapsed" class="product-images-grid">
                  <div
                    v-for="(img, index) in images"
                    :key="index"
                    class="product-image-item"
                    :class="{ 'selected': isImageSelected(img) }"
                    @click="toggleImageSelection(img)"
                  >
                    <el-image
                      :src="img"
                      fit="cover"
                      class="product-image"
                    >
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline" />
                      </div>
                    </el-image>
                    <div v-if="isImageSelected(img)" class="selected-badge">
                      <i class="el-icon-check" />
                    </div>
                  </div>
                </div>
              </div>

              <!-- 模板选择区域 -->
              <div class="template-section">
                <div class="section-header" @click="templateCollapsed = !templateCollapsed">
                  <span class="section-title">
                    <i class="el-icon-picture-outline-round" /> 选择模板（可选）
                  </span>
                  <div class="section-actions">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-plus"
                      style="color: #1EB7E6;"
                      @click.stop="showTemplateDialog"
                    >
                      添加模板
                    </el-button>
                    <i :class="templateCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" class="collapse-icon" />
                  </div>
                </div>

                <div v-show="!templateCollapsed" class="template-content">
                  <div v-if="templates && templates.length > 0" class="template-list">
                    <div
                      v-for="template in templates"
                      :key="template.id"
                      class="template-item"
                      :class="{ 'selected': selectedTemplateId === template.id }"
                      @click="selectedTemplateId = template.id"
                    >
                      <el-image
                        :src="template.image_url"
                        fit="cover"
                        class="template-image"
                      >
                        <div slot="error" class="image-slot">
                          <i class="el-icon-picture-outline" />
                        </div>
                      </el-image>
                      <div class="template-info">
                        <div class="template-name">{{ template.name }}</div>
                        <el-button
                          type="text"
                          size="mini"
                          icon="el-icon-delete"
                          style="color: #f56c6c;"
                          @click.stop="deleteTemplate(template.id)"
                        >
                          删除
                        </el-button>
                      </div>
                      <div v-if="selectedTemplateId === template.id" class="selected-badge">
                        <i class="el-icon-check" />
                      </div>
                    </div>
                  </div>
                  <el-empty v-else description="暂无模板" :image-size="60" />
                </div>
              </div>
            </div>

            <!-- 可滚动的内容区域 -->
            <div class="scrollable-content">
              <!-- 分组列表 -->
              <div class="groups-container">
                <div
                  v-for="(group, groupIndex) in form.groups"
                  :key="groupIndex"
                  class="group-item"
                  :class="{ 'active-group': currentGroupIndex === groupIndex }"
                  @click="currentGroupIndex = groupIndex"
                >
                  <div class="group-header">
                    <span class="group-title">
                      分组 {{ groupIndex + 1 }}
                      <el-tag v-if="currentGroupIndex === groupIndex" type="success" size="mini" effect="dark">
                        当前分组
                      </el-tag>
                    </span>
                    <el-input
                      v-model="group.name"
                      placeholder="输入分组名称（可选）"
                      size="small"
                      style="width: 180px; margin-left: 10px;"
                      @click.stop
                    />
                    <el-button
                      size="small"
                      type="primary"
                      icon="el-icon-magic-stick"
                      style="background-color: #1EB7E6; border-color: #1EB7E6; margin-left: 10px;"
                      :loading="group.generating"
                      :disabled="!group.images || group.images.length === 0"
                      @click.stop="generateGroupImage(groupIndex)"
                    >
                      生成图片
                    </el-button>
                    <el-button
                      size="small"
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      style="margin-left: 10px;"
                      @click.stop="removeGroup(groupIndex)"
                    />
                  </div>

                  <div class="group-content">
                    <!-- 图片上传区域 -->
                    <div class="upload-container">
                      <div
                        v-loading="group.imageLoading"
                        class="paste-area"
                        tabindex="0"
                        @paste="(e) => handlePaste(e, groupIndex)"
                        @click="focusPasteArea"
                        @dragover.prevent
                        @drop="(e) => handleDrop(e, groupIndex)"
                      >
                        <div v-if="!group.images || !group.images.length" class="paste-tip">
                          <i class="el-icon-picture-outline" />
                          <div>点击后粘贴图片或拖拽图片</div>
                          <div style="font-size: 12px; color: #909399; margin-top: 5px;">也可以粘贴图片URL链接</div>
                        </div>
                        <div v-else class="paste-images">
                          <div
                            v-for="(img, imgIndex) in group.images"
                            :key="imgIndex"
                            class="image-item"
                            :class="{ 'dragging': dragState.dragIndex === imgIndex && dragState.groupIndex === groupIndex }"
                            draggable="true"
                            @dragstart="handleImageDragStart(groupIndex, imgIndex, $event)"
                            @dragover.prevent="handleImageDragOver(groupIndex, imgIndex, $event)"
                            @drop.prevent="handleImageDragDrop(groupIndex, imgIndex, $event)"
                            @dragend="handleImageDragEnd($event)"
                          >
                            <el-image
                              :src="img"
                              fit="cover"
                              class="preview-image"
                              :preview-src-list="group.images"
                              :initial-index="imgIndex"
                            >
                              <div slot="error" class="image-slot">
                                <i class="el-icon-picture-outline" />
                              </div>
                            </el-image>
                            <i class="el-icon-delete delete-icon" @click.stop="removeImage(groupIndex, imgIndex)" />
                            <div class="drag-handle">
                              <i class="el-icon-s-grid" />
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- URL输入区域 -->
                      <div class="url-input-area">
                        <el-input
                          v-model="group.imageUrlInput"
                          placeholder="或者输入图片URL链接"
                          class="url-input"
                          size="small"
                          @keyup.enter="addImageUrl(groupIndex)"
                        >
                          <el-button slot="append" :disabled="!group.imageUrlInput" @click="addImageUrl(groupIndex)">添加</el-button>
                        </el-input>
                      </div>

                      <!-- 文件选择按钮 -->
                      <div class="file-upload-area">
                        <el-button type="text" icon="el-icon-folder-opened" size="small" @click="triggerFileInput(groupIndex)">选择文件</el-button>
                        <input
                          :ref="`fileInput${groupIndex}`"
                          type="file"
                          style="display: none"
                          accept="image/*"
                          multiple
                          @change="(e) => handleFileChange(e, groupIndex)"
                        >
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 添加分组按钮 -->
              <div class="add-group-btn-container">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  @click="addGroup"
                >
                  添加分组
                </el-button>
              </div>
            </div>
          </div>

          <!-- 右侧：AI生成信息和结果展示区域 -->
          <div class="right-panel">
            <!-- AI 生成信息展示区 -->
            <div class="ai-info-section">
              <div class="ai-info-header">
                <i class="el-icon-cpu" /> AI 生成信息
              </div>
              <div class="ai-info-content">
                <div v-if="!aiGenerating && generatedImages.length === 0" class="ai-placeholder">
                  <i class="el-icon-picture-outline" />
                  <p>点击左侧分组的"生成图片"按钮开始生成</p>
                </div>
                <div v-else-if="aiGenerating" class="ai-generating">
                  <el-progress
                    :percentage="generateProgress"
                    :status="generateProgress === 100 ? 'success' : ''"
                  />
                  <div class="generating-text">
                    <i class="el-icon-loading" /> {{ generateStatus }}
                  </div>
                </div>
                <div v-if="generateLog" class="ai-log">
                  <pre>{{ generateLog }}</pre>
                </div>
              </div>
            </div>

            <!-- 瀑布流图片展示区 -->
            <div class="waterfall-section">
              <div class="waterfall-header">
                <span>
                  <i class="el-icon-picture" /> 已生成图片 ({{ generatedImages.length }})
                </span>
                <el-button
                  v-if="generatedImages.length > 0"
                  type="text"
                  size="small"
                  @click="clearAllImages"
                >
                  清空全部
                </el-button>
              </div>
              <div class="waterfall-container">
                <div
                  v-for="(img, index) in generatedImages"
                  :key="index"
                  class="waterfall-item"
                >
                  <el-image
                    :src="img.url"
                    fit="cover"
                    class="waterfall-image"
                    :preview-src-list="generatedImages.map(i => i.url)"
                    :initial-index="index"
                  >
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline" />
                    </div>
                  </el-image>
                  <div class="waterfall-item-info">
                    <div class="image-name">{{ img.name || '未命名' }}</div>
                    <div class="image-actions">
                      <el-button type="text" size="mini" @click.stop="downloadImage(img.url, img.name)">
                        下载
                      </el-button>
                      <el-button type="text" size="mini" @click.stop="deleteGeneratedImage(index)">
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 添加模板对话框 -->
    <el-dialog
      title="添加模板"
      :visible.sync="templateDialogVisible"
      width="500px"
      :append-to-body="true"
    >
      <el-form :model="newTemplate" label-width="100px">
        <el-form-item label="模板名称" required>
          <el-input v-model="newTemplate.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="图片URL" required>
          <el-input
            v-model="newTemplate.image_url"
            type="textarea"
            :rows="3"
            placeholder="请输入模板图片URL，例如：https://tools.kikimami.com/cms/api/image/..."
          />
          <div style="margin-top: 5px; font-size: 12px; color: #909399;">
            示例：https://tools.kikimami.com/cms/api/image/generated_images/p_14/20251009_143327_2055d175.webp
          </div>
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input
            v-model="newTemplate.description"
            type="textarea"
            :rows="2"
            placeholder="请输入模板描述（可选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="templateDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          style="background-color: #1EB7E6; border-color: #1EB7E6;"
          @click="addTemplate"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Post as UploadBase64Image } from '@/api/cms/image'
import { Get as GetCatalogImages, Delete as DeleteCatalogImage, GenerateDirect } from '@/api/crm/crmcatalogimage'
import { Get as GetTemplates, Post as CreateTemplate, Delete as DeleteTemplate } from '@/api/crm/crmcatalogimagetemplate'

export default {
  name: 'CatalogImageGenerator',
  props: {
    // 报价单ID
    quoteId: {
      type: [Number, String],
      default: null
    },
    // 产品图片列表（从报价单传入）
    images: {
      type: Array,
      default: () => []
    },
    // 按钮文本
    buttonText: {
      type: String,
      default: '生成目录册图片'
    },
    // 按钮类型
    buttonType: {
      type: String,
      default: 'primary'
    },
    // 按钮大小
    buttonSize: {
      type: String,
      default: 'small'
    },
    // 按钮图标
    buttonIcon: {
      type: String,
      default: 'el-icon-magic-stick'
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      generating: false,

      // 当前激活的分组索引（用于添加选中的产品图片）
      currentGroupIndex: 0,

      form: {
        groups: [
          {
            name: '',
            images: [],
            imageUrlInput: '',
            imageLoading: false,
            generating: false
          }
        ]
      },

      // 拖拽状态
      dragState: {
        groupIndex: null,
        dragIndex: null,
        dragOverIndex: null
      },

      // AI生成相关
      aiGenerating: false,
      generateProgress: 0,
      generateStatus: '',
      generateLog: '',
      generatedImages: [], // [{url: '', name: '', groupIndex: 0}]

      // 模板管理
      templates: [],
      selectedTemplateId: null,
      templateDialogVisible: false,
      newTemplate: {
        name: '',
        image_url: '',
        description: ''
      },

      // 折叠状态
      productImagesCollapsed: false,
      templateCollapsed: false
    }
  },
  computed: {
    // 是否可以生成
    canGenerate() {
      // 至少有一个分组包含图片
      return this.form.groups.some(group => group.images && group.images.length > 0)
    }
  },
  methods: {
    // 显示对话框
    showDialog() {
      this.dialogVisible = true
    },

    // 对话框打开时
    handleDialogOpen() {
      // 重置当前分组索引
      this.currentGroupIndex = 0
      // 加载模板列表
      this.loadTemplates()
      // 加载已生成的图片
      this.loadGeneratedImages()
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
      this.resetForm()
    },

    // 判断图片是否在当前分组中
    isImageSelected(imageUrl) {
      if (!this.form.groups[this.currentGroupIndex]) return false
      return this.form.groups[this.currentGroupIndex].images.includes(imageUrl)
    },

    // 切换图片选择状态（添加或移除）
    toggleImageSelection(imageUrl) {
      const currentGroup = this.form.groups[this.currentGroupIndex]
      if (!currentGroup) return

      const index = currentGroup.images.indexOf(imageUrl)
      if (index > -1) {
        // 已存在，移除
        currentGroup.images.splice(index, 1)
        this.$message.info('已从当前分组移除图片')
      } else {
        // 不存在，添加
        currentGroup.images.push(imageUrl)
        this.$message.success('已添加图片到当前分组')
      }
    },

    // 重置表单
    resetForm() {
      this.form.groups = [
        {
          name: '',
          images: [],
          imageUrlInput: '',
          imageLoading: false
        }
      ]
    },

    // 添加分组
    addGroup() {
      this.form.groups.push({
        name: '',
        images: [],
        imageUrlInput: '',
        imageLoading: false
      })
      this.$message.success('分组已添加')
    },

    // 删除分组
    removeGroup(groupIndex) {
      if (this.form.groups.length === 1) {
        this.$message.warning('至少需要保留一个分组')
        return
      }
      this.$confirm('确定要删除这个分组吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.groups.splice(groupIndex, 1)
        this.$message.success('分组已删除')
      }).catch(() => {})
    },

    // 处理粘贴事件
    handlePaste(event, groupIndex) {
      console.log('粘贴事件触发', groupIndex)
      const data = event.clipboardData || window.clipboardData
      if (data) {
        // 先检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('检测到图片URL:', textContent)
          this.form.groups[groupIndex].images.push(textContent)
          this.$message.success('图片URL已添加')
          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        console.log('剪贴板项目数量:', items.length)
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          console.log('项目类型:', items[i].kind, items[i].type)
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            console.log('获取到图片文件:', blob)
            this.handleImageUpload(blob, groupIndex)
            foundImage = true
          }
        }
        if (!foundImage) {
          this.$message.warning('未检测到图片，请确保复制的是图片内容或图片URL')
        }
      } else {
        this.$message.error('无法获取剪贴板数据')
      }
    },

    // 检查字符串是否是图片URL
    isImageUrl(str) {
      try {
        const url = new URL(str)
        const pathLower = url.pathname.toLowerCase()
        const isImageExt =
          pathLower.endsWith('.jpg') ||
          pathLower.endsWith('.jpeg') ||
          pathLower.endsWith('.png') ||
          pathLower.endsWith('.gif') ||
          pathLower.endsWith('.webp') ||
          pathLower.endsWith('.svg') ||
          pathLower.endsWith('.bmp')
        return isImageExt || /\.(jpg|jpeg|png|gif|webp|svg|bmp)/i.test(url.search)
      } catch (e) {
        return false
      }
    },

    // 处理拖拽事件
    handleDrop(event, groupIndex) {
      event.preventDefault()
      const data = event.dataTransfer
      if (data) {
        // 检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('拖拽的图片URL:', textContent)
          this.form.groups[groupIndex].images.push(textContent)
          this.$message.success('图片URL已添加')
          return
        }

        // 否则检查是否为实际图片文件
        const files = data.files
        let foundImage = false
        for (let i = 0; i < files.length; i++) {
          if (files[i].type.indexOf('image/') !== -1) {
            this.handleImageUpload(files[i], groupIndex)
            foundImage = true
          }
        }

        if (!foundImage) {
          this.$message.warning('未检测到图片文件')
        }
      }
    },

    // 处理图片上传
    handleImageUpload(blob, groupIndex) {
      if (!blob) {
        this.$message.error('图片文件无效')
        return
      }

      this.$message.info('正在处理图片...')
      this.form.groups[groupIndex].imageLoading = true

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const base64Data = e.target.result

          // 调用上传接口
          UploadBase64Image({
            file_data: base64Data,
            directory_id: -1,
            keyword: 'catalog-image-generator'
          })
            .then(response => {
              this.$message.success('图片上传成功')
              this.form.groups[groupIndex].images.push(response.data.url)
              this.form.groups[groupIndex].imageLoading = false
            })
            .catch(error => {
              this.$message.error('图片上传失败: ' + (error.message || '未知错误'))
              this.form.groups[groupIndex].imageLoading = false
            })
        } catch (err) {
          console.error('处理图片失败:', err)
          this.$message.error('图片处理失败')
          this.form.groups[groupIndex].imageLoading = false
        }
      }
      reader.onerror = () => {
        console.error('读取文件失败')
        this.$message.error('读取文件失败')
        this.form.groups[groupIndex].imageLoading = false
      }
      reader.readAsDataURL(blob)
    },

    // 获取焦点
    focusPasteArea(event) {
      event.preventDefault()
    },

    // 移除图片
    removeImage(groupIndex, imgIndex) {
      if (this.form.groups[groupIndex].images && this.form.groups[groupIndex].images.length > imgIndex) {
        this.form.groups[groupIndex].images.splice(imgIndex, 1)
        this.$message.success('图片已删除')
      }
    },

    // 添加图片URL
    addImageUrl(groupIndex) {
      const imageUrl = this.form.groups[groupIndex].imageUrlInput
      if (!imageUrl) {
        this.$message.warning('请输入图片URL')
        return
      }

      if (!this.isImageUrl(imageUrl)) {
        this.$message.warning('请输入有效的图片URL')
        return
      }

      // 检查是否已存在
      if (this.form.groups[groupIndex].images.includes(imageUrl)) {
        this.$message.warning('该图片URL已存在')
        return
      }

      this.form.groups[groupIndex].images.push(imageUrl)
      this.form.groups[groupIndex].imageUrlInput = ''
      this.$message.success('图片URL已添加')
    },

    // 触发文件输入
    triggerFileInput(groupIndex) {
      const refName = `fileInput${groupIndex}`
      const fileInput = this.$refs[refName]
      if (fileInput && fileInput[0]) {
        fileInput[0].click()
      }
    },

    // 处理文件变化
    handleFileChange(event, groupIndex) {
      const files = event.target.files
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        this.handleImageUpload(file, groupIndex)
      }
      // 清空文件输入，允许重复选择同一文件
      event.target.value = ''
    },

    // 图片拖拽开始
    handleImageDragStart(groupIndex, imgIndex, event) {
      this.dragState.groupIndex = groupIndex
      this.dragState.dragIndex = imgIndex
      event.dataTransfer.effectAllowed = 'move'
    },

    // 图片拖拽悬停
    handleImageDragOver(groupIndex, imgIndex, event) {
      event.preventDefault()
      event.dataTransfer.dropEffect = 'move'
    },

    // 图片拖拽放置
    handleImageDragDrop(groupIndex, imgIndex, event) {
      event.preventDefault()

      if (this.dragState.groupIndex === groupIndex &&
          this.dragState.dragIndex !== null &&
          this.dragState.dragIndex !== imgIndex) {
        // 同一分组内排序
        const draggedItem = this.form.groups[groupIndex].images[this.dragState.dragIndex]
        const newImages = [...this.form.groups[groupIndex].images]

        newImages.splice(this.dragState.dragIndex, 1)
        const insertIndex = this.dragState.dragIndex < imgIndex ? imgIndex - 1 : imgIndex
        newImages.splice(insertIndex, 0, draggedItem)

        this.form.groups[groupIndex].images = newImages
        this.$message.success('图片排序已更新')
      }

      // 重置拖拽状态
      this.dragState.groupIndex = null
      this.dragState.dragIndex = null
    },

    // 图片拖拽结束
    handleImageDragEnd(event) {
      this.dragState.groupIndex = null
      this.dragState.dragIndex = null
    },

    // 预览图片
    previewImage(imageUrl) {
      // 使用 el-image 的内置预览功能，此方法不再需要
      console.log('预览图片:', imageUrl)
    },

    // 生成单个分组的图片
    async generateGroupImage(groupIndex) {
      const group = this.form.groups[groupIndex]

      if (!group.images || group.images.length === 0) {
        this.$message.warning('请先添加图片到分组')
        return
      }

      try {
        group.generating = true
        this.aiGenerating = true
        this.generateProgress = 0
        this.generateStatus = '正在准备生成...'
        this.generateLog = `开始生成分组 ${groupIndex + 1}: ${group.name || '未命名'}\n图片数量: ${group.images.length}\n\n`

        // 准备请求数据
        const requestData = {
          images: group.images,
          group_name: group.name || `分组 ${groupIndex + 1}`,
          group_index: groupIndex
        }

        // 如果有报价单ID，添加quote_id
        if (this.quoteId) {
          requestData.quote_id = this.quoteId
        }

        // 如果选择了模板，添加template_id
        if (this.selectedTemplateId) {
          requestData.template_id = this.selectedTemplateId
          const selectedTemplate = this.templates.find(t => t.id === this.selectedTemplateId)
          if (selectedTemplate) {
            this.generateLog += `使用模板: ${selectedTemplate.name}\n`
          }
        }

        this.generateProgress = 10
        this.generateStatus = '正在调用AI生成图片...'
        this.generateLog += '正在调用AI...\n'

        // 调用API生成图片
        const response = await GenerateDirect(requestData)

        if (response.success) {
          this.generateProgress = 100
          this.generateStatus = '生成完成！'
          this.generateLog += '图片生成成功！\n'
          this.generateLog += `图片URL: ${response.data.image_url}\n`

          // 添加到生成图片列表
          this.generatedImages.push({
            id: response.data.id,
            url: response.data.image_url,
            name: response.data.group_name,
            groupIndex: response.data.group_index
          })

          this.$message.success('图片生成成功并已保存！')
        } else {
          throw new Error(response.msg || '生成失败')
        }
      } catch (error) {
        console.error('生成失败:', error)
        const errorMsg = error.response && error.response.data && error.response.data.msg
          ? error.response.data.msg
          : error.message || '未知错误'
        this.generateLog += `\n错误: ${errorMsg}\n`
        this.$message.error('生成失败: ' + errorMsg)
        this.generateProgress = 0
        this.generateStatus = '生成失败'
      } finally {
        group.generating = false
        this.aiGenerating = false
      }
    },

    // 下载图片
    downloadImage(url, name) {
      const link = document.createElement('a')
      link.href = url
      link.download = `${name || '目录册图片'}.webp`
      link.click()
    },

    // 删除已生成的图片
    async deleteGeneratedImage(index) {
      const image = this.generatedImages[index]

      this.$confirm('确定要删除这张图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          // 如果有数据库ID，先删除数据库记录
          if (image.id) {
            const response = await DeleteCatalogImage(image.id)
            if (!response.success) {
              this.$message.error(response.msg || '删除失败')
              return
            }
          }

          // 从列表中移除
          this.generatedImages.splice(index, 1)
          this.$message.success('删除成功')
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },

    // 清空所有生成的图片
    async clearAllImages() {
      this.$confirm('确定要清空所有已生成的图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          // 删除所有有ID的记录
          const deletePromises = this.generatedImages
            .filter(img => img.id)
            .map(img => DeleteCatalogImage(img.id))

          if (deletePromises.length > 0) {
            await Promise.all(deletePromises)
          }

          this.generatedImages = []
          this.$message.success('清空成功')
        } catch (error) {
          console.error('清空失败:', error)
          this.$message.error('部分删除失败')
          // 即使失败也清空列表
          this.generatedImages = []
        }
      }).catch(() => {})
    },

    // ===== 模板管理方法 =====

    // 加载模板列表
    async loadTemplates() {
      try {
        const response = await GetTemplates()
        if (response.success) {
          this.templates = response.data || []
        }
      } catch (error) {
        console.error('加载模板列表失败:', error)
      }
    },

    // 加载已生成的图片
    async loadGeneratedImages() {
      if (!this.quoteId) {
        console.log('没有quoteId，跳过加载已生成图片')
        return
      }

      try {
        const response = await GetCatalogImages(null, `quote_id=${this.quoteId}`)
        if (response.success && response.data && response.data.data) {
          // 清空现有列表
          this.generatedImages = []

          // 将数据库中的图片添加到列表
          response.data.data.forEach(item => {
            if (item.result_image_url && item.status === 'completed') {
              this.generatedImages.push({
                id: item.id,
                url: item.result_image_url,
                name: item.name || '目录册图片',
                groupIndex: 0,
                created_at: item.create_at
              })
            }
          })

          console.log(`加载了 ${this.generatedImages.length} 张已生成图片`)
        }
      } catch (error) {
        console.error('加载已生成图片失败:', error)
      }
    },

    // 打开添加模板对话框
    showTemplateDialog() {
      this.newTemplate = {
        name: '',
        image_url: '',
        description: ''
      }
      this.templateDialogVisible = true
    },

    // 添加模板
    async addTemplate() {
      if (!this.newTemplate.name) {
        this.$message.warning('请输入模板名称')
        return
      }
      if (!this.newTemplate.image_url) {
        this.$message.warning('请输入模板图片URL')
        return
      }

      try {
        const response = await CreateTemplate(this.newTemplate)
        if (response.success) {
          this.$message.success('模板添加成功')
          this.templateDialogVisible = false
          await this.loadTemplates()
        } else {
          this.$message.error(response.msg || '添加失败')
        }
      } catch (error) {
        console.error('添加模板失败:', error)
        this.$message.error('添加失败')
      }
    },

    // 删除模板
    async deleteTemplate(templateId) {
      this.$confirm('确定要删除这个模板吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const response = await DeleteTemplate(templateId)
          if (response.success) {
            this.$message.success('删除成功')
            // 如果删除的是当前选中的模板，清空选择
            if (this.selectedTemplateId === templateId) {
              this.selectedTemplateId = null
            }
            await this.loadTemplates()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除模板失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.catalog-image-generator {
  display: inline-block;
}

.catalog-drawer >>> .el-drawer__body {
  padding: 0;
  overflow: hidden;
  position: relative;
}

.catalog-generator-content {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 左右分栏布局 */
.layout-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧面板 */
.left-panel {
  width: 40%;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e4e7ed;
  background-color: #f9fafc;
}

.left-panel .fixed-header {
  flex-shrink: 0;
  padding: 20px;
}

.left-panel .scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px 20px 20px;
}

/* 右侧面板 */
.right-panel {
  width: 60%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  overflow: hidden;
}

/* 产品图片选择区域样式 */
.product-images-section {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9fafc;
}

/* 模板选择区域 */
.template-section {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9fafc;
}

.template-content {
  padding: 15px;
  transition: all 0.3s ease;
}

.template-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.template-item {
  position: relative;
  border: 2px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.template-item:hover {
  border-color: #1EB7E6;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(30, 183, 230, 0.2);
}

.template-item.selected {
  border-color: #1EB7E6;
  box-shadow: 0 0 8px rgba(30, 183, 230, 0.4);
}

.template-image {
  width: 100%;
  height: 100px;
  display: block;
}

.template-info {
  padding: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #e4e7ed;
  background-color: #fff;
}

.template-name {
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #fff;
  border-radius: 4px 4px 0 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.section-header:hover {
  background-color: #f5f7fa;
}

.section-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.collapse-icon {
  font-size: 14px;
  color: #909399;
  transition: transform 0.3s;
}

.section-title {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.section-title i {
  color: #409EFF;
  margin-right: 5px;
}

.section-hint {
  font-size: 12px;
  color: #909399;
}

.product-images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 10px;
  padding: 15px;
  max-height: 250px;
  overflow-y: auto;
  transition: all 0.3s ease;
}

.product-image-item {
  position: relative;
  width: 100%;
  height: 100px;
  border: 2px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
}

.product-image-item:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-color: #409EFF;
}

.product-image-item.selected {
  border-color: #67C23A;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.3);
}

.product-image {
  width: 100%;
  height: 100%;
}

.selected-badge {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  background-color: #67C23A;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.groups-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.group-item {
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  background-color: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
}

.group-item:hover {
  border-color: #1EB7E6;
  box-shadow: 0 2px 8px rgba(30, 183, 230, 0.2);
}

.group-item.active-group {
  border: 2px solid #67C23A;
  background-color: #f0f9ff;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.group-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.group-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.group-content {
  padding: 10px 0;
}

.upload-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.paste-area {
  padding: 15px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  text-align: center;
  cursor: pointer;
  background-color: #fff;
  transition: all 0.3s;
  min-height: 100px;
  outline: none;
}

.paste-area:hover,
.paste-area:focus {
  border-color: #1EB7E6;
  background-color: #f0f9ff;
}

.paste-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 70px;
  color: #909399;
}

.paste-tip i {
  font-size: 28px;
  color: #1EB7E6;
  margin-bottom: 8px;
}

.paste-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 5px;
  min-height: 70px;
}

.image-item {
  position: relative;
  width: 80px;
  height: 80px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: grab;
}

.image-item:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-item:active {
  cursor: grabbing;
}

.image-item.dragging {
  opacity: 0.5;
  transform: rotate(5deg) scale(1.1);
  z-index: 1000;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.preview-image {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.preview-image >>> .el-image__inner {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-icon {
  position: absolute;
  top: 3px;
  right: 3px;
  background-color: rgba(245, 108, 108, 0.9);
  color: white;
  border-radius: 50%;
  padding: 3px;
  cursor: pointer;
  font-size: 10px;
  transition: all 0.3s;
}

.delete-icon:hover {
  background-color: #f56c6c;
  transform: scale(1.1);
}

.drag-handle {
  position: absolute;
  bottom: 2px;
  left: 2px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 3px;
  padding: 2px 3px;
  font-size: 8px;
  cursor: grab;
  transition: all 0.3s;
  opacity: 0;
}

.image-item:hover .drag-handle {
  opacity: 1;
}

.drag-handle:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

.drag-handle:active {
  cursor: grabbing;
}

.url-input-area {
  display: flex;
  align-items: center;
}

.url-input {
  flex: 1;
}

.file-upload-area {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.add-group-btn-container {
  text-align: center;
  margin: 20px 0;
}

/* 图片加载错误占位符 */
.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #c0c4cc;
  font-size: 24px;
}

/* AI信息展示区 */
.ai-info-section {
  flex-shrink: 0;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #fafbfc;
}

.ai-info-header {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

.ai-info-header i {
  color: #1EB7E6;
  margin-right: 8px;
}

.ai-info-content {
  min-height: 120px;
}

.ai-placeholder {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.ai-placeholder i {
  font-size: 48px;
  display: block;
  margin-bottom: 10px;
}

.ai-generating {
  padding: 10px 0;
}

.generating-text {
  margin-top: 10px;
  color: #1EB7E6;
  font-size: 14px;
}

.generating-text i {
  margin-right: 5px;
}

.ai-log {
  margin-top: 15px;
  max-height: 150px;
  overflow-y: auto;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

.ai-log pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.5;
  color: #606266;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 瀑布流展示区 */
.waterfall-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 20px;
}

.waterfall-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.waterfall-header i {
  color: #409EFF;
  margin-right: 5px;
}

.waterfall-container {
  flex: 1;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  align-content: start;
}

.waterfall-item {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
}

.waterfall-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #1EB7E6;
}

.waterfall-image {
  width: 100%;
  height: 200px;
}

.waterfall-item-info {
  padding: 10px;
}

.image-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-actions {
  display: flex;
  gap: 10px;
}

.image-actions .el-button {
  padding: 0;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .group-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .image-item {
    width: 60px;
    height: 60px;
  }

  .drag-handle {
    opacity: 1;
  }
}
</style>
